package com.gxcommunication.sociallearn.http.service;

import android.content.Context;


import com.google.gson.JsonParseException;
import com.gxcommunication.sociallearn.app.MyApplication;
import com.gxcommunication.sociallearn.base.bean.BaseBean;
import com.gxcommunication.sociallearn.utils.CommonSharePreferenceUtils;
import com.gxcommunication.sociallearn.utils.LogHelper;
import com.gxcommunication.sociallearn.utils.NetUtil;
import com.gxcommunication.sociallearn.widget.progress.MyProgressDialog;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Observer基类
 * 
 * @param <T>
 */
public abstract class HttpObserver<T extends BaseBean> implements Observer<T> {

    private MyProgressDialog mDialog;
    private Context mContext;

    private boolean isShowProgress = false;

    /**
     * 创建进度条实例
     */
    public void createProgressDialog(Context cxt, boolean canCancle) {
        if (mContext == null){
            return;
        }
        try {
            if (mDialog == null) {
                mDialog = new MyProgressDialog(mContext);
                mDialog.setCanceledOnTouchOutside(canCancle);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //进度条显示
    public void showProgress() {

        if (mContext == null){
            return;
        }

        try {
            if (mDialog == null) {
                mDialog = new MyProgressDialog(mContext);
                mDialog.setCanceledOnTouchOutside(true);
            }
            if (mDialog.isShowing()) return;
            mDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //隐藏进度条
    public void hideProgress() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }


    public HttpObserver() {

    }

    public HttpObserver(Context context, boolean isShowProgress, boolean canCancle) {

        mContext = context;
        this.isShowProgress = isShowProgress;
        if (isShowProgress){
            createProgressDialog(context,canCancle);
        }
    }

    /**
     * 可以统一处理返回值及相关操作
     *
     * @param result
     */
    @Override
    public  void onNext(T result){
      //  Log.e("onNext----->", GsonUtlils.objectToJson(result));
        hideProgress();

        if (result.getCode() == 0) {
            onSuccess(result);
        } else if (result.getCode() == 99990401 || result.getCode() == 403 ) {  //错误码401 303 登录
            CommonSharePreferenceUtils.clearUser();

            onFailed(result.getCode(), result.getMsg());
        } else if (result.getCode() == 300) {
            onFailed(result.getCode(), result.getMsg());
        }else if (result.getCode() == 4001 ){//淘宝授权
            onFailed(result.getCode(), result.getMsg());
            onTaoBaoAuto( result.getMsg());
        }else {
            onFailed(result.getCode(), result.getMsg());
        }

    }



    /**
     * 请求成功回调
     *
     * @param result 服务端返回的数据
     */
    public abstract void onSuccess(T result);

    /**
     * 请求失败的回调 (非 200的情况)，开发者手动去触发
     *
     * @param moreInfo 错误信息数据
     */
    public void onFailed(int errorCode, String moreInfo) {
    }


    public void onTaoBaoAuto( String moreInfo){

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {
        if (NetUtil.isNetConnected(MyApplication.getInstance())){

            if (isShowProgress){
                showProgress();
            }

        }else {
            //没有网络的时候，调用error方法，并且切断与上游的联系
            if (!d.isDisposed()) {
                d.dispose();
                onFailed(0, "无网络");
                return;
            }
        }
    }

    /**
     * 可以统一处理请求失败的错误
     *
     * @param e
     */
    @Override
//    public abstract void onError(Throwable e);
    public  void onError(Throwable e){
        //关闭弹窗进度条
        hideProgress();
        onErrors(e);
    }

    /**
     * 连接异常时回调，手动触发
     */
    public void onErrors(@NonNull Throwable e) {
        if (e instanceof UnknownHostException || e instanceof ConnectException) {//无网络
            solveException(ExceptionType.BAD_NETWORK);
        } else if (e instanceof JsonParseException || e instanceof JSONException ||
                e instanceof ParseException) {//解析异常
            solveException(ExceptionType.PARSE_DATA_ERROR);
        } else if (e instanceof HttpException) {//http异常，比如 404 500
            solveException(ExceptionType.UNFOUND_ERROR);
        } else if (e instanceof SocketTimeoutException) {//连接超时
            solveException(ExceptionType.TIMEOUT_ERROR);
        } else {//未知错误
            solveException(ExceptionType.UNKNOWN_ERROR);
        }

    }

    /**
     * 对于异常情况的统一处理
     *
     * @param type 异常的类型
     */
    public void solveException(ExceptionType type) {
        switch (type) {
            case BAD_NETWORK:

                onFailed(0, "无网络");

                break;
            case PARSE_DATA_ERROR:

                onFailed(0, "数据解析异常");

                break;
            case UNFOUND_ERROR:

                onFailed(0, "地址链接错误");

                break;
            case TIMEOUT_ERROR:

                onFailed(0, "请求超时");

                break;
            case UNKNOWN_ERROR:

                onFailed(0, "未知错误");

                break;
        }
    }

    public enum ExceptionType {
        /**
         * 无网络
         */
        BAD_NETWORK,
        /**
         * 数据解析异常
         */
        PARSE_DATA_ERROR,
        /**
         * 找不到相关连接
         */
        UNFOUND_ERROR,
        /**
         * 连接超时
         */
        TIMEOUT_ERROR,
        /**
         * 未知错误
         */
        UNKNOWN_ERROR
    }

}

